<script setup lang="ts">
import { ElDialog, ElMessage, ElScrollbar } from 'element-plus'
import { propTypes } from '@/utils/propTypes'
import { computed, useAttrs, reactive, onMounted } from 'vue'
import { Paging } from '@/config/public'
import { useI18n } from '@/hooks/web/useI18n'
import { ModuleTree } from '@/components/Tree'
import { selectModule, queryDictionary } from '@/api/develop'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import { useAppStore } from '@/store/modules/app'

const localeStore = useLocaleStoreWithOut()
const curLang = localeStore.getCurrentLocale.lang
const appStore = useAppStore()
const { t } = useI18n()

defineOptions({
  name: 'DictSelectDialog'
})

const emit = defineEmits(['selected', 'cancel'])

const props = defineProps({
  modelValue: propTypes.bool.def(false),
  title: propTypes.string.def('不用管，已废弃')
})

const state = reactive({
  searchKey: '',
  // 表格數據
  tableView: [{}],
  // 分頁相關屬性
  totalCount: 0,
  pageSizes: Paging.sizes,
  queryBody: {
    key: '',
    pageNo: 1,
    pageSize: 10,
    params: {
      'Q_dic.status_I_EQ': 1
    },
    sortField: '',
    sortOrder: ''
  },
  lstModNameField: 'moduleName',
  dictNameField: 'dictName',
  curModuleId: '',
  moduleList: [{}],
  curSelect: {} as any
})

onMounted(async () => {
  if (curLang == 'en') {
    state.lstModNameField = 'enModuleName'
    state.dictNameField = 'enName'
  } else if (curLang == 'zh_HK') {
    state.lstModNameField = 'hkModuleName'
    state.dictNameField = 'hkName'
  }
  state.moduleList = await selectModule()
  init()
})

const changePage = (page) => {
  state.queryBody.pageNo = page
  init()
}
const changePageSize = (pageSize) => {
  state.queryBody.pageSize = pageSize
  state.queryBody.pageNo = 1
  init()
}

// 搜索
const handleSearch = () => {
  state.queryBody.key = state.searchKey
  init()
}
//重置查询
const resetSearch = () => {
  state.searchKey = ''
  state.queryBody.params['Q_dic.module_id_S_IN'] = ''
  handleSearch()
}
//点击模块树节点
const handleNodeClick = (data) => {
  state.queryBody.params['Q_dic.module_id_S_IN'] = data
  state.curModuleId = data.split(',')[0]
  handleSearch()
}

//渲染页面的接口
const init = async () => {
  appStore.setFooter(false)
  state.tableView = []
  await queryDictionary(state.queryBody)
    .then((res) => {
      const result = res as any
      var data = result.result.data
      state.tableView = data
      state.totalCount = result.result.totalCount
    })
    .catch(() => {})
}

const getBindValue = computed(() => {
  const delArr: string[] = ['title']
  const attrs = useAttrs()
  const obj = { ...attrs, ...props }
  for (const key in obj) {
    if (delArr.indexOf(key) !== -1) {
      delete obj[key]
    }
  }
  return obj
})

//选择行变化
const changeRow = (currentRow) => {
  if (currentRow) {
    state.curSelect = currentRow
  } else {
    state.curSelect = null
  }
}

//双击行,直接选中
const dblclickRow = (row) => {
  if (row) {
    state.curSelect = row
    clickOK()
  } else {
    state.curSelect = null
  }
}

//确定按钮事件
const clickOK = () => {
  if (!state.curSelect) {
    ElMessage.warning(t('common.selectOne'))
    return
  }
  emit('selected', state.curSelect)
}
//取消按钮事件
const clickCancel = () => {
  emit('cancel')
}
</script>

<template>
  <ElDialog
    v-bind="getBindValue"
    lock-scroll
    draggable
    :fullscreen="false"
    :close-on-click-modal="false"
  >
    <template #title>
      <div class="flex justify-between">
        <slot name="title">
          <span style="font-weight: bold; font-size: 14px; color: #666">
            {{ $t('dialog.orderNoTitle') }}</span
          >
        </slot>
      </div>
    </template>
    <ElScrollbar style="margin: -18px -8px">
      <div>
        <!-- 搜索條件卡片 -->
        <el-card>
          <el-row :gutter="10" style="padding: 5px 5px; line-height: 28px" align="middle">
            <el-col :sm="5" :md="4" style="text-align: right; font-size: 12px">{{
              $t('common.searchKey')
            }}</el-col>
            <el-col :sm="19" :md="12" style="text-align: left">
              <el-input
                v-model="state.searchKey"
                @keyup.enter="handleSearch"
                :placeholder="
                  $t('common.inputText') + $t('dataDict.name') + '/' + $t('dataDict.key')
                "
              />
            </el-col>
            <el-col :sm="24" :md="8" style="text-align: right">
              <div style="margin-right: -5px">
                <el-button @click="handleSearch" type="primary" size="small" plain
                  ><Icon icon="ic:outline-search" /><span>{{ $t('common.query') }}</span>
                </el-button>
                <el-button @click="resetSearch" type="info" size="small" plain>
                  <Icon icon="icon-park-solid:clear-format" /><span>{{ $t('common.reset') }}</span>
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-card>
        <el-container class="mainArea">
          <el-aside width="180px">
            <ModuleTree @node-click="handleNodeClick" />
          </el-aside>
          <el-main class="formcard">
            <!-- 搜索結果表格 -->
            <el-table
              :data="state.tableView"
              tooltip-effect="light"
              style="width: 100%; border: 1px solid #ddd; font-size: 12px"
              stripe
              row-key="id"
              default-expand-all
              highlight-current-row
              @current-change="changeRow"
              @row-dblclick="dblclickRow"
              :header-cell-style="{
                background: 'var(--el-color-primary-light-9)',
                color: '#409eff'
              }"
            >
              <el-table-column type="index" min-width="60">
                <template #header>
                  <div style="margin-bottom: -10px">
                    <Icon
                      icon="ant-design:field-number-outlined"
                      size="24"
                      :title="$t('common.number')"
                  /></div>
                </template>
              </el-table-column>
              <el-table-column
                :prop="state.dictNameField"
                :label="$t('dataDict.name')"
                show-overflow-tooltip
                min-width="120"
              />
              <el-table-column prop="dicKey" :label="$t('dataDict.key')" min-width="90" />
              <el-table-column
                prop="sortNo"
                :label="$t('common.sort')"
                min-width="90"
                align="center"
              />
              <el-table-column
                prop="isFixed"
                :label="$t('dataDict.fixed')"
                min-width="80"
                align="center"
              >
                <template #default="{ row }">
                  <span v-if="row.isFixed == 1">{{ $t('common.yes') }}</span>
                  <span v-else>{{ $t('common.no') }}</span>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分頁器 -->
            <div class="demo-pagination-block"
              ><el-pagination
                v-model:currentPage="state.queryBody.pageNo"
                v-model:page-size="state.queryBody.pageSize"
                @current-change="changePage"
                @size-change="changePageSize"
                :page-sizes="state.pageSizes"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="state.totalCount"
                style="font-size: 12px !important"
            /></div>
          </el-main>
        </el-container>
      </div>
    </ElScrollbar>
    <template #footer>
      <el-button @click="clickCancel">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="clickOK">{{ $t('common.ok') }}</el-button>
    </template>
  </ElDialog>
</template>

<style lang="less" scoped>
.@{elNamespace}-dialog__header {
  border-bottom: 1px solid var(--tags-view-border-color);
}

.@{elNamespace}-dialog__footer {
  border-top: 1px solid var(--tags-view-border-color);
}

.is-hover {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}
:deep(.el-card__header) {
  border-bottom: 0;
  box-sizing: border-box;
}

:deep(.el-select .el-option .el-input .el-select-dropdown__item) {
  font-size: 12px;
}

:deep(.el-input__inner) {
  &::placeholder {
    font-size: 12px;
  }
  font-size: 12px;
}

:deep(.el-dialog__body) {
  padding: 10px 50px;
}
:deep(.v-footer) {
  height: 0px;
}
.mainArea {
  overflow-x: hidden;
  height: 420px;
}
.formcard {
  margin: -12px -19px 0 -15px;
}
// 分頁器樣式
.demo-pagination-block {
  display: flex;
  justify-content: center;
  justify-items: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
:deep(.el-pagination__sizes > .el-select) {
  margin-top: -3px;
}
:deep(.el-pager li) {
  font-size: 12px;
  height: 28px;
  margin-top: -1px;
}
:deep(span.el-pagination__jump) {
  font-size: 12px;
}
:deep(span.el-pagination__total) {
  font-size: 12px;
}
:deep(.btn-next) {
  height: 28px;
}
:deep(.el-pagination button) {
  height: 28px;
}
</style>
